package com.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Package: com.aop
 * @ClassName: BaseAspect
 * @Author: wulongkai
 * @CreateTime: 2024/3/6 11:00
 * @Description:
 */
@Slf4j
public class BaseAspect {

    /**
     * 获取切面方法上包含的指定注解
     *
     * @param joinPoint
     * @param <T>
     * @return
     * @throws NoSuchMethodException
     */
    public <T extends Annotation> T getDeclaredAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
        try {
            // 反射获取目标类
            Class<?> targetClass = joinPoint.getTarget().getClass();
            // 获取方法名
            String methodName = joinPoint.getSignature().getName();
            // 拿到方法对应的参数类型
            Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
            // 根据类、方法、参数类型（重载）获取到方法的具体信息
            Method objMethod = targetClass.getMethod(methodName, parameterTypes);
            // 拿到方法定义的注解信息
            T annotation = objMethod.getDeclaredAnnotation(annotationClass);
            return annotation;

        } catch (Exception e) {
            return null;
        }
    }
}
